package com.yao.controller;

import com.yao.bean.R;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.endpoint.FrameworkEndpoint;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * Copyright (C), 2022-2022, 姚兵
 * Author: 32210
 * Date: 2022/11/2 20:57
 * FileName: LogoutHandler
 * Description:
 */


@RestController
public class LogoutHandler {


    @Autowired
    ConsumerTokenServices consumerTokenServices;



    @Autowired
    RedisTokenStore redisTokenStore;

    String userNameClientId="client:user:%s:%s";


    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/oauth/logout")
    public R revokeToken(String access_token) {

        OAuth2Authentication authentication = redisTokenStore.readAuthentication(access_token);
        String clientId = authentication.getOAuth2Request().getClientId();

        User user = (User) authentication.getUserAuthentication().getPrincipal();
        if (consumerTokenServices.revokeToken(access_token)){
            redisTemplate.delete(String.format(userNameClientId,clientId,user.getUsername()));
            return R.ok().data("成功");
        }else{
            return R.err().data("失败");
        }
    }


}
